package com.roy.wakeupes.utils;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author fhey
 * @date 2023-04-20 11:15:58
 * @description: 文件工具类
 */
public class FileUtil {
    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    //获取新文件的全路径
    public static String getNewFileFullPath(String sourceFilePath, String destFilePath, String ext) {
        File destFile = new File(destFilePath);
        if (destFile.isFile()) {
            return destFilePath;
        }
        File sourceFile = new File(sourceFilePath);
        String sourceFileName = sourceFile.getName();
        if (sourceFile.isFile()) {
            return destFilePath + File.separator + sourceFileName.substring(0, sourceFileName.lastIndexOf(StrUtil.DOT)) + StrUtil.DOT + ext;
        }
        return destFilePath + File.separator + sourceFileName + StrUtil.DOT + ext;
    }

    //判断文件是否是图片
    public static boolean isImage(File file) throws IOException {
        FileInputStream is = new FileInputStream(file);
        byte[] bytes = new byte[8];
        is.read(bytes);
        is.close();
        String type = bytesToHexString(bytes).toUpperCase();
        if (type.contains("FFD8FF") //JPEG(jpg)
                || type.contains("89504E47") //PNG
                || type.contains("47494638") //GIF
                || type.contains("49492A00") //TIFF(tif)
                || type.contains("424D") //Bitmap(bmp)
        ) {
            return true;
        }
        return false;
    }

    //将文件头转换成16进制字符串
    public static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }
        return builder.toString();
    }

}

